<template>
  <div class="activity-list">
    <div class="activity-header">
      <h4 class="section-title">动态 ({{ activities.length }})</h4>
    </div>
    
    <div class="activities-container" v-loading="loading">
      <el-empty v-if="!loading && activities.length === 0" description="暂无动态记录" :image-size="100" />
      
      <div v-else class="activity-timeline">
        <div
          v-for="activity in activities"
          :key="activity.id"
          class="activity-item"
        >
          <div class="activity-icon">
            <el-icon :size="20" :color="activity.iconColor">
              <component :is="activity.icon" />
            </el-icon>
          </div>
          <div class="activity-content">
            <div class="activity-header-info">
              <UserAvatar
                v-if="getUserById(activity.userId)"
                :user="getUserById(activity.userId)"
                size="small"
                circle
                class="activity-user-avatar"
              />
              <span class="activity-user" :title="activity.userName || '系统'">{{ activity.userName || '系统' }}</span>
              <span class="activity-action">{{ activity.action }}</span>
              <span class="activity-time">{{ formatDateTime(activity.created_at) }}</span>
            </div>
            <div v-if="activity.details" class="activity-details">
              {{ activity.details }}
            </div>
            <div v-if="activity.changes && activity.changes.length > 0" class="activity-changes">
              <div v-for="(change, index) in activity.changes" :key="index" class="change-item">
                <span class="change-field">{{ change.field }}：</span>
                <span class="change-old">{{ formatChangeValue(change.field, change.oldValue) || '—' }}</span>
                <el-icon class="change-arrow"><ArrowRight /></el-icon>
                <span class="change-new">{{ formatChangeValue(change.field, change.newValue) || '—' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, markRaw } from 'vue'
import { ElEmpty, ElIcon } from 'element-plus'
import { withDefaults } from 'vue'
import { 
  User, 
  Edit, 
  Plus, 
  Delete, 
  Link, 
  Document, 
  ArrowRight,
  Check,
  Clock
} from '@element-plus/icons-vue'
import { formatDateTime } from '@/utils/date'
import UserAvatar from '@/components/ui/UserAvatar.vue'
import type { User as UserType } from '@/types/user'

interface ActivityChange {
  field: string
  oldValue?: string
  newValue?: string
}

interface Activity {
  id: string
  type: string
  action: string
  userName?: string
  userId?: string
  created_at: string
  details?: string
  changes?: ActivityChange[]
  icon?: any
  iconColor?: string
}

interface StatusOption {
  value: string
  label: string
}

interface PriorityOption {
  value: string
  label: string
}

interface UserOption {
  id: string
  name: string
}

interface Props {
  entityType: 'requirement' | 'task' | 'defect'
  entityId: string
  requirement?: any // 需求对象，用于生成动态
  statusOptions?: StatusOption[] // 状态选项，用于映射中文名称
  priorityOptions?: PriorityOption[] // 优先级选项，用于映射中文名称
  users?: UserOption[] // 用户列表，用于查找更新人姓名
}

const props = withDefaults(defineProps<Props>(), {
  statusOptions: () => [],
  priorityOptions: () => [],
  users: () => []
})

const loading = ref(false)
const activities = ref<Activity[]>([])

// 根据活动类型获取图标和颜色
const getActivityIcon = (type: string) => {
  const iconMap: Record<string, { icon: any; color: string }> = {
    created: { icon: markRaw(Plus), color: '#67C23A' },
    updated: { icon: markRaw(Edit), color: '#409EFF' },
    deleted: { icon: markRaw(Delete), color: '#F56C6C' },
    comment: { icon: markRaw(User), color: '#909399' },
    attachment: { icon: markRaw(Document), color: '#E6A23C' },
    linked: { icon: markRaw(Link), color: '#409EFF' },
    status_changed: { icon: markRaw(Check), color: '#67C23A' },
    assigned: { icon: markRaw(User), color: '#409EFF' },
    time_updated: { icon: markRaw(Clock), color: '#E6A23C' }
  }
  return iconMap[type] || { icon: markRaw(Edit), color: '#909399' }
}

// 映射状态为中文
const mapStatusToLabel = (status: string | null | undefined): string => {
  if (!status) return '—'
  return props.statusOptions?.find(opt => opt.value === status)?.label || status
}

// 映射优先级为中文
const mapPriorityToLabel = (priority: string | null | undefined): string => {
  if (!priority) return '—'
  return props.priorityOptions?.find(opt => opt.value === priority)?.label || priority
}

// 格式化变更值（根据字段类型进行映射）
const formatChangeValue = (field: string, value: string | null | undefined): string => {
  if (!value) return ''
  // 根据字段类型进行映射
  if (field === '状态' || field === 'status') {
    return mapStatusToLabel(value)
  }
  if (field === '优先级' || field === 'priority') {
    return mapPriorityToLabel(value)
  }
  // 时间字段格式化
  if (field.includes('时间') || field.includes('日期') || field.includes('date') || field.includes('time')) {
    return formatDateTime(value)
  }
  return value
}

// 获取用户名称（通过ID查找）
const getUserName = (userId: string | null | undefined, fallbackName?: string): string => {
  if (!userId) return fallbackName || '系统'
  const user = props.users?.find(u => u.id === userId)
  return user?.name || fallbackName || '系统'
}

// 根据用户ID获取用户对象（用于头像显示）
const getUserById = (userId?: string | null): UserType | null => {
  if (!userId) return null
  const userOption = props.users?.find(u => u.id === userId)
  if (!userOption) return null
  return {
    id: userOption.id,
    name: userOption.name,
    username: userOption.name,
    email: '',
    avatar: (userOption as any).avatar || '',
    roles: [],
    status: 'active',
    is_verified: false,
    created_at: '',
    updated_at: ''
  } as UserType
}

// 生成动态记录
const generateActivities = () => {
  const entity = props.requirement // 可能是 requirement、task 或 defect
  if (!entity || !entity.id) {
    activities.value = []
    return
  }

  const activityList: Activity[] = []
  
  // 根据实体类型生成不同的动态记录
  if (props.entityType === 'defect') {
    generateDefectActivities(entity, activityList)
  } else if (props.entityType === 'task') {
    generateTaskActivities(entity, activityList)
  } else {
    // 默认处理需求
    generateRequirementActivities(entity, activityList)
  }

  // 按时间倒序排序
  activityList.sort((a, b) => {
    return new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
  })

  activities.value = activityList
}

// 生成缺陷动态记录
const generateDefectActivities = (defect: any, activityList: Activity[]) => {
  // 创建缺陷
  if (defect.created_at) {
    const reporterName = defect.reporter_name || getUserName(defect.reporter_id, '系统')
    activityList.push({
      id: `created-${defect.id}`,
      type: 'created',
      action: '创建了缺陷',
      userName: reporterName,
      userId: defect.reporter_id,
      created_at: defect.created_at,
      details: `缺陷标题：${defect.title || ''}`,
      ...getActivityIcon('created')
    })
  }

  // 发现时间
  if (defect.found_date) {
    const reporterName = defect.reporter_name || getUserName(defect.reporter_id, '系统')
    activityList.push({
      id: `found-date-${defect.id}`,
      type: 'time_updated',
      action: '设置了发现时间',
      userName: reporterName,
      userId: defect.reporter_id,
      created_at: defect.found_date,
      changes: [{
        field: '发现时间',
        newValue: formatDateTime(defect.found_date)
      }],
      ...getActivityIcon('time_updated')
    })
  }

  // 解决时间
  if (defect.resolved_date) {
    const resolverName = defect.resolver_name || getUserName(defect.resolver_id, defect.assignee_name || '系统')
    activityList.push({
      id: `resolved-date-${defect.id}`,
      type: 'time_updated',
      action: '标记为已解决',
      userName: resolverName,
      userId: defect.resolver_id || defect.assignee_id,
      created_at: defect.resolved_date,
      changes: [{
        field: '解决时间',
        newValue: formatDateTime(defect.resolved_date)
      }],
      ...getActivityIcon('time_updated')
    })
  }

  // 验证时间
  if (defect.verified_date) {
    const verifierName = defect.verifier_name || getUserName(defect.verifier_id, '系统')
    activityList.push({
      id: `verified-date-${defect.id}`,
      type: 'time_updated',
      action: '标记为已验证',
      userName: verifierName,
      userId: defect.verifier_id,
      created_at: defect.verified_date,
      changes: [{
        field: '验证时间',
        newValue: formatDateTime(defect.verified_date)
      }],
      ...getActivityIcon('time_updated')
    })
  }

  // 完成时间
  if (defect.completed_at) {
    const completerName = defect.completer_name || getUserName(defect.completer_id, defect.assignee_name || '系统')
    activityList.push({
      id: `completed-at-${defect.id}`,
      type: 'time_updated',
      action: '设置了完成时间',
      userName: completerName,
      userId: defect.completer_id || defect.assignee_id,
      created_at: defect.completed_at,
      changes: [{
        field: '完成时间',
        newValue: formatDateTime(defect.completed_at)
      }],
      ...getActivityIcon('time_updated')
    })
  }

  // 实际完成时间
  if (defect.actual_completed_at) {
    const completerName = defect.completer_name || getUserName(defect.completer_id, defect.assignee_name || '系统')
    activityList.push({
      id: `actual-completed-at-${defect.id}`,
      type: 'time_updated',
      action: '设置了实际完成时间',
      userName: completerName,
      userId: defect.completer_id || defect.assignee_id,
      created_at: defect.actual_completed_at,
      changes: [{
        field: '实际完成时间',
        newValue: formatDateTime(defect.actual_completed_at)
      }],
      ...getActivityIcon('time_updated')
    })
  }

  // 状态变更
  if (defect.status) {
    const statusLabel = mapStatusToLabel(defect.status)
    const updatedByName = defect.updated_by_name || getUserName(defect.updated_by_id, defect.reporter_name)
    activityList.push({
      id: `status-${defect.id}`,
      type: 'status_changed',
      action: '更新了状态',
      userName: updatedByName,
      userId: defect.updated_by_id || defect.reporter_id,
      created_at: defect.updated_at || defect.created_at,
      changes: [{
        field: '状态',
        newValue: statusLabel
      }],
      ...getActivityIcon('status_changed')
    })
  }

  // 负责人变更
  if (defect.assignee_name) {
    const updatedByName = defect.updated_by_name || getUserName(defect.updated_by_id, defect.reporter_name)
    activityList.push({
      id: `assignee-${defect.id}`,
      type: 'assigned',
      action: '分配了负责人',
      userName: updatedByName,
      userId: defect.updated_by_id || defect.reporter_id,
      created_at: defect.updated_at || defect.created_at,
      changes: [{
        field: '负责人',
        newValue: defect.assignee_name
      }],
      ...getActivityIcon('assigned')
    })
  }

  // 优先级变更
  if (defect.priority) {
    const priorityLabel = mapPriorityToLabel(defect.priority)
    const updatedByName = defect.updated_by_name || getUserName(defect.updated_by_id, defect.reporter_name)
    activityList.push({
      id: `priority-${defect.id}`,
      type: 'updated',
      action: '更新了优先级',
      userName: updatedByName,
      userId: defect.updated_by_id || defect.reporter_id,
      created_at: defect.updated_at || defect.created_at,
      changes: [{
        field: '优先级',
        newValue: priorityLabel
      }],
      ...getActivityIcon('updated')
    })
  }

  // 更新时间（如果有更新且不是创建时间）
  if (defect.updated_at && defect.updated_at !== defect.created_at) {
    const updatedByName = defect.updated_by_name || getUserName(defect.updated_by_id, defect.reporter_name)
    activityList.push({
      id: `updated-${defect.id}-${defect.updated_at}`,
      type: 'updated',
      action: '更新了缺陷',
      userName: updatedByName,
      userId: defect.updated_by_id || defect.reporter_id,
      created_at: defect.updated_at,
      details: '缺陷信息已更新',
      ...getActivityIcon('updated')
    })
  }
}

// 生成任务动态记录（占位，可根据需要实现）
const generateTaskActivities = (task: any, activityList: Activity[]) => {
  // TODO: 实现任务动态记录生成
  if (task.created_at) {
    const creatorName = task.creator_name || getUserName(task.created_by, '系统')
    activityList.push({
      id: `created-${task.id}`,
      type: 'created',
      action: '创建了任务',
      userName: creatorName,
      userId: task.created_by,
      created_at: task.created_at,
      ...getActivityIcon('created')
    })
  }
}

// 生成需求动态记录（原有逻辑）
const generateRequirementActivities = (req: any, activityList: Activity[]) => {

  // 创建需求
  if (req.created_at) {
    // 优先使用 reporter_name，如果没有则通过 reporter_id 查找
    const reporterName = req.reporter_name || getUserName(req.reporter_id, '系统')
    activityList.push({
      id: `created-${req.id}`,
      type: 'created',
      action: '创建了需求',
      userName: reporterName,
      userId: req.reporter_id,
      created_at: req.created_at,
      ...getActivityIcon('created')
    })
  }

  // 更新时间（如果有更新且不是创建时间）
  if (req.updated_at && req.updated_at !== req.created_at) {
    // 优先使用 updated_by_name，如果没有则通过 updated_by_id 查找，最后使用 reporter_name
    const updatedByName = req.updated_by_name || getUserName(req.updated_by_id, req.reporter_name)
    activityList.push({
      id: `updated-${req.id}-${req.updated_at}`,
      type: 'updated',
      action: '更新了需求',
      userName: updatedByName,
      userId: req.updated_by_id || req.reporter_id,
      created_at: req.updated_at,
      details: '需求信息已更新',
      ...getActivityIcon('updated')
    })
  }

  // 状态变更
  if (req.status) {
    // 映射状态为中文
    const statusLabel = mapStatusToLabel(req.status)
    // 优先使用 updated_by_name，如果没有则通过 updated_by_id 查找，最后使用 reporter_name
    const updatedByName = req.updated_by_name || getUserName(req.updated_by_id, req.reporter_name)
    activityList.push({
      id: `status-${req.id}`,
      type: 'status_changed',
      action: '更新了状态',
      userName: updatedByName,
      userId: req.updated_by_id || req.reporter_id,
      created_at: req.updated_at || req.created_at,
      changes: [{
        field: '状态',
        newValue: statusLabel
      }],
      ...getActivityIcon('status_changed')
    })
  }

  // 负责人变更
  if (req.assignee_name) {
    // 优先使用 updated_by_name，如果没有则通过 updated_by_id 查找，最后使用 reporter_name
    const updatedByName = req.updated_by_name || getUserName(req.updated_by_id, req.reporter_name)
    activityList.push({
      id: `assignee-${req.id}`,
      type: 'assigned',
      action: '分配了负责人',
      userName: updatedByName,
      userId: req.updated_by_id || req.reporter_id,
      created_at: req.updated_at || req.created_at,
      changes: [{
        field: '负责人',
        newValue: req.assignee_name
      }],
      ...getActivityIcon('assigned')
    })
  }

  // 优先级变更
  if (req.priority) {
    // 映射优先级为中文
    const priorityLabel = mapPriorityToLabel(req.priority)
    // 优先使用 updated_by_name，如果没有则通过 updated_by_id 查找，最后使用 reporter_name
    const updatedByName = req.updated_by_name || getUserName(req.updated_by_id, req.reporter_name)
    activityList.push({
      id: `priority-${req.id}`,
      type: 'updated',
      action: '更新了优先级',
      userName: updatedByName,
      userId: req.updated_by_id || req.reporter_id,
      created_at: req.updated_at || req.created_at,
      changes: [{
        field: '优先级',
        newValue: priorityLabel
      }],
      ...getActivityIcon('updated')
    })
  }

  // 关联版本
  if (req.versions && req.versions.length > 0) {
    req.versions.forEach((version: any, index: number) => {
      // 优先使用 updated_by_name，如果没有则通过 updated_by_id 查找，最后使用 reporter_name
      const updatedByName = req.updated_by_name || getUserName(req.updated_by_id, req.reporter_name)
      activityList.push({
        id: `version-${req.id}-${index}`,
        type: 'linked',
        action: '关联了版本',
        userName: updatedByName,
        userId: req.updated_by_id || req.reporter_id,
        created_at: version.associated_at || req.updated_at || req.created_at,
        details: `版本：${version.name || version.version_number || version.id}`,
        ...getActivityIcon('linked')
      })
    })
  }

  // 按时间倒序排序
  activityList.sort((a, b) => {
    return new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
  })

  activities.value = activityList
}

// 监听需求变化
watch(
  () => props.requirement,
  () => {
    generateActivities()
  },
  { deep: true, immediate: true }
)

onMounted(() => {
  generateActivities()
})
</script>

<style scoped lang="scss">
.activity-list {
  padding: 16px 0;
}

.activity-header {
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.activities-container {
  min-height: 200px;
}

.activity-timeline {
  position: relative;
  padding-left: 32px;
}

.activity-item {
  position: relative;
  padding-bottom: 24px;
  padding-left: 40px;

  &:not(:last-child)::before {
    content: '';
    position: absolute;
    left: 15px;
    top: 32px;
    bottom: -8px;
    width: 2px;
    background-color: #e4e7ed;
  }

  &:last-child {
    padding-bottom: 0;
  }
}

.activity-icon {
  position: absolute;
  left: 0;
  top: 0;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.activity-content {
  flex: 1;
}

.activity-header-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.activity-user-avatar {
  flex-shrink: 0;
}

.activity-user {
  font-weight: 600;
  color: #409EFF;
  cursor: default;
  
  &:hover {
    color: #66b1ff;
    text-decoration: underline;
  }
}

.activity-action {
  color: #606266;
}

.activity-time {
  color: #909399;
  font-size: 12px;
  margin-left: auto;
}

.activity-details {
  color: #606266;
  margin-top: 4px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 13px;
}

.activity-changes {
  margin-top: 8px;
  padding: 12px;
  background-color: #fafafa;
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

.change-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 0;
  font-size: 13px;

  &:not(:last-child) {
    border-bottom: 1px solid #f0f2f5;
    padding-bottom: 8px;
    margin-bottom: 8px;
  }
}

.change-field {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.change-old {
  color: #909399;
  text-decoration: line-through;
  padding: 2px 8px;
  background-color: #fef0f0;
  border-radius: 3px;
}

.change-arrow {
  color: #c0c4cc;
  font-size: 14px;
}

.change-new {
  color: #67c23a;
  font-weight: 500;
  padding: 2px 8px;
  background-color: #f0f9ff;
  border-radius: 3px;
}
</style>

